package com.mz.ozy.activity.find;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jaeger.library.StatusBarUtil;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.jude.rollviewpager.hintview.IconHintView;
import com.jude.rollviewpager.hintview.ShapeHintView;
import com.mz.ozy.R;
import com.mz.ozy.activity.MainActivity;
import com.mz.ozy.adapter.BannerAdapter;
import com.mz.ozy.adapter.HotTopicAdapter;
import com.mz.ozy.adapter.IntegralBannerAdapter;
import com.mz.ozy.adapter.SignDayAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.HomeBean;
import com.mz.ozy.bean.MeBean;
import com.mz.ozy.bean.MyIntegralBean;
import com.mz.ozy.bean.SignDayBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.MyIntegralPresenter;
import com.mz.ozy.mvp.view.MyIntegralContract;
import com.mz.ozy.utils.AppUtils;
import com.mz.ozy.utils.CalendarUtils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.dialog.BaseDialog;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 我的积分
 */
public class MyIntegralActivity extends BaseActivity<MyIntegralContract.View, MyIntegralPresenter> implements MyIntegralContract.View {

    @BindView(R.id.iv_top_bg)
    ImageView mIvTopBg;
    @BindView(R.id.tv_sign)
    TextView mBtSign;
    @BindView(R.id.rv_day)
    RecyclerView mRvDay;
    @BindView(R.id.tv_sign_day)
    TextView mTvSignDay;
    @BindView(R.id.tv_reissue_card)
    TextView mTvReissueCard;
    @BindView(R.id.rv_hot_topic)
    RecyclerView mRvHotTopic;
    @BindView(R.id.rollPagerView)
    RollPagerView mRollPagerView;
    @BindView(R.id.iv_bannerPager)
    ImageView mIvBannerView;
//    @BindView(R.id.tv_integral)
//    TextView mTvIntegral;

    private IntegralBannerAdapter mBannerAdapter;
    private HotTopicAdapter mHotTopicAdapter;
    private SignDayAdapter mDayAdapter;
    private List<SignDayBean> mDayList = new ArrayList<>();
    private MyIntegralBean mIntegralBean;
    private String todayStr;
    private List<HomeBean.BannerListBean> mBannerListBeans = new ArrayList<>();
    private String toDayValue;
    private boolean isSigned = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_integral);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.c_60b0b0), 0);
        ButterKnife.bind(this);
        titleBar = findViewById(R.id.titleBar);
        tvBack = findViewById(R.id.iv_back);
        setTitleBarMargin();
        tvBack.setImageResource(R.mipmap.kt_y);
//        addTestData();
        initCurDate();
        initView();
    }

    @Override
    public void onBackPressed() {
        MainActivity.tabHost.setCurrentTab(0);
    }

    private void initCurDate() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        todayStr = sdf.format(cal.getTime());
    }

    /**
     * 设置沉浸式状态栏时，要把标题栏往下移动状态栏的高度
     */
    protected void setTitleBarMargin() {
        int length = AppUtils.getStatusBarHeight(this);
        //注意布局是哪种Layout
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(titleBar.getLayoutParams());
        lp.setMargins(0, length, 0, 0);
        titleBar.setLayoutParams(lp);
    }

    private void addTestData() {
        mDayList.add(new SignDayBean(0, "2020-04-09"));
        mDayList.add(new SignDayBean(0, "2020-04-10"));
        mDayList.add(new SignDayBean(1, "2020-04-11"));
        mDayList.add(new SignDayBean(1, "2020-04-12"));
        mDayList.add(new SignDayBean(2, "2020-04-13"));
        mDayList.add(new SignDayBean(2, "2020-04-14"));
        mDayList.add(new SignDayBean(2, "2020-04-15"));
    }

    private void initView() {
        mRollPagerView.setAnimationDurtion(500);
//        mRollPagerView.setHintView(new ColorPointHintView(this, getResources().getColor(R.color.c_90ff), getResources().getColor(R.color.white)));
        mRollPagerView.setHintView(new ShapeHintView(this) {
            @Override
            public Drawable makeFocusDrawable() {
                return ContextCompat.getDrawable(MyIntegralActivity.this, R.drawable.bg_solid_white_1dp);
            }

            @Override
            public Drawable makeNormalDrawable() {
                return ContextCompat.getDrawable(MyIntegralActivity.this, R.drawable.bg_solid_4dffffff_1dp);
            }
        });
        mBannerAdapter = new IntegralBannerAdapter(this, mBannerListBeans);
        mRollPagerView.setAdapter(mBannerAdapter);

        mDayAdapter = new SignDayAdapter(mDayList);
        mRvDay.setHasFixedSize(true);
        final LinearLayoutManager manager = new LinearLayoutManager(this) {
            //禁止水平滑动
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvDay.setLayoutManager(manager);
        mRvDay.setAdapter(mDayAdapter);

        mRvHotTopic.setLayoutManager(new LinearLayoutManager(this));
        mRvHotTopic.setNestedScrollingEnabled(false);
        mHotTopicAdapter = new HotTopicAdapter(null);
        mRvHotTopic.setAdapter(mHotTopicAdapter);
        mHotTopicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                if(!Constants.isVip){
//                    showVipDialog();
//                    return;
//                }
                final MyIntegralBean.TopicListBean item = mHotTopicAdapter.getItem(position);
                Intent intent = new Intent(MyIntegralActivity.this, TopicDetailActivity.class);
                intent.putExtra("id", item.getId() + "");
                startActivity(intent);
            }
        });
        mDayAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                switch (R.id.tv_indicator) {
                    case R.id.tv_indicator:
                        final SignDayBean item = mDayAdapter.getItem(position);
                        final int state = item.getState();
                        if (state == 2) {
                            final String datetime = item.getDay().substring(0, 4) + item.getDay().substring(5, 7) + item.getDay().substring(8, 10);
                            mPresenter.onMakeUp(MyIntegralActivity.this, datetime);
                        }
                        break;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.onInfo(this);
        mPresenter.getMeInfo(this, false);
    }

    @OnClick({R.id.tv_sign, R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_sign:
//                if (mIntegralBean != null && mIntegralBean.getIsSignin() == 0) {
                mPresenter.onSign(this);
//                }
                break;
            case R.id.iv_back:
//                if(!Constants.isVip){
//                    showVipDialog();
//                    return;
//                }
                Intent intent = new Intent(this, HomePageActivity.class);
                intent.putExtra("id", Constants.uid);
                startActivity(intent);
                break;
        }
    }

    /**
     * 显示签到成功弹窗
     */
    private void showSignDialog(String title, String msg) {
        final BaseDialog dialog = new BaseDialog(this, R.layout.dialog_sign, Gravity.CENTER, true);
        dialog.setText(R.id.tv_value, title)
                .setText(R.id.tv_get_integral_tip, msg)
                .setOnViewClick(R.id.btn_confirm, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.toggleDialog();
                    }
                });
        dialog.toggleDialog();
    }

    private void handDateData() {
        mDayList.clear();
        //1.获取本周日期,2019-05-10
        String[] weekDays = CalendarUtils.getCurrentWeekDay();
        boolean todayPre = true;
        for (int i = 0; i < weekDays.length; i++) {
            SignDayBean bean = new SignDayBean();
            //1.设置日期
            bean.setDay(weekDays[i]);
            if (todayPre) {
                if (weekDays[i].equals(todayStr)) {
                    todayPre = false;
                } else {
                    bean.setState(2);
                }
            }
            if (weekDays[i].equals(todayStr)) {
                toDayValue = mIntegralBean.getCheckSetList().get(i).getPvalue();
            }
            //2.设置积分，取到当月几号,对比取得该号对应积分
            bean.setPrize(mIntegralBean.getCheckSetList().get(i).getPvalue());
            //3.设置状态,找到对应日期的签到状态,能找到日期则是已签到
            if (mIntegralBean.getCheckList() != null && mIntegralBean.getCheckList().size() > 0) {
                for (int k = 0; k < mIntegralBean.getCheckList().size(); k++) {
                    String testStr = mIntegralBean.getCheckList().get(k).getInittime();
                    final String realDay = testStr.substring(0, 4) + "-" + testStr.substring(4, 6) + "-" + testStr.substring(6, 8);
                    if (realDay.equals(weekDays[i])) {
                        bean.setState(1);
                        if (realDay.endsWith(todayStr)) {
                            isSigned = true;
                            mBtSign.setText("今天已签到");
                        }
                        break;
                    }
                }
            }
            mDayList.add(bean);
        }
        mDayAdapter.notifyDataSetChanged();
    }

    @Override
    public void getgetMeInfoSuccess(MeBean bean) {
        GlideUtils.loadAvatar(this, tvBack, bean.getUseravatar());
    }

    @Override
    public void onInfoSuccess(MyIntegralBean bean) {
        mIntegralBean = bean;
//        mBtSign.setBackgroundResource(bean.getIsSignin() == 0 ? R.mipmap.sign_btn : R.mipmap.signed_btn);
        final List<MyIntegralBean.CheckListBean> checkList = mIntegralBean.getCheckList();
        mTvSignDay.setText(bean.getFrequency() + "天");
        mTvReissueCard.setText(bean.getSignCardNum() + "");
        mBannerListBeans.clear();
        List<HomeBean.BannerListBean> bannerList = bean.getBannerList();
        if (bannerList != null && bannerList.size() > 0) {
            for (HomeBean.BannerListBean bannerListBean : bannerList) {
                mBannerListBeans.add(bannerListBean);
            }
        } else {
            mRollPagerView.setVisibility(View.GONE);
            mIvBannerView.setVisibility(View.VISIBLE);
        }
        mBannerAdapter.notifyDataSetChanged();
//        //填充日期数据
        handDateData();
        final List<MyIntegralBean.TopicListBean> huatList = mIntegralBean.getHuatList();
        if (huatList != null && huatList.size() > 0) {
            mHotTopicAdapter.setNewData(huatList);
        }
    }

    @Override
    public void onSignSuccess(JSONObject result) {
        //赠送积分金额
        showSignDialog("签到成功", "恭喜您获得" + toDayValue + "积分");
        mPresenter.onInfo(this);
    }

    @Override
    public void onMakeUpSuccess(JSONObject result) {
        showSignDialog("补签成功", "补签扣取补签卡" + 1 + "张");
        mPresenter.onInfo(this);
    }
}
